package com.basic.library.utils;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Base64;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.basic.library.base.BaseApplication;
import com.basic.library.base.BaseConstants;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


public class FileUtils {

    // private static String TAG = "FileUtils";
    // private static boolean DEBUG = false; //是否Debug
    // private static final int BUFFER = 8192;

    // 是否有SD卡
    public static boolean isHasSDCard() {
        boolean isHasSDCard = false;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) {
            isHasSDCard = true;
        }
        return isHasSDCard;
    }

    public static String getCachePath() {
        String cachePath;
        Context context = BaseApplication.getInstance();
        if (isHasSDCard()) {
            //外部存储可用
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            //外部存储不可用
            cachePath = context.getCacheDir().getPath();
        }
        return cachePath;
    }

    public static String getFilePath() {
        String filePath;
        Context context = BaseApplication.getInstance();
        if (isHasSDCard()) {
            //外部存储可用
            filePath = context.getExternalFilesDir(null).getPath();
        } else {
            //外部存储不可用
            filePath = context.getFilesDir().getPath();
        }
        return filePath;
    }

    /**
     * encodeBase64File:(将文件转成base64 字符串). <br/>
     *
     * @param path 文件路径
     * @return
     * @throws Exception
     * @author guhaizhou@126.com
     * @since JDK 1.6
     */
    public static String encodeBase64File(String path) throws Exception {
        if (path == null || !new File(path).exists()) {
            return null;
        }
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeToString(buffer, Base64.DEFAULT);
    }

    /*
     * 读取文本文件 param String
     */
    public static String readTextFile(File file) throws IOException {
        String text = null;
        InputStream is = null;
        if (isHasSDCard()) {
            try {
                is = new FileInputStream(file);
                text = readTextInputStream(is);
                ;
            } finally {
                if (is != null) {
                    is.close();
                }
            }
        }
        return text;
    }

    /*
     * 读取文本文件 param InputStream
     */
    public static String readTextInputStream(InputStream is) throws IOException {
        StringBuffer strbuffer = new StringBuffer();
        String line;
        BufferedReader reader = null;
        if (!isHasSDCard()) {
            return null;
        }
        try {
            reader = new BufferedReader(new InputStreamReader(is));
            while ((line = reader.readLine()) != null) {
                strbuffer.append(line).append("\r\n");
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return strbuffer.toString();
    }

    /*
     * 写入文本文件 param String
     */
    public static void writeTextFile(File file, String str) throws IOException {
        DataOutputStream out = null;
        if (isHasSDCard()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try {
                out = new DataOutputStream(new FileOutputStream(file));
                out.write(str.getBytes());
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
    }

    /*
     * 写入文本文件 param inStream
     */
    public static void writeTextFile(File file, InputStream inStream)
            throws IOException {
        FileOutputStream outStream = null;
        if (isHasSDCard()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            try {
                outStream = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = inStream.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }
            } finally {
                if (outStream != null) {
                    outStream.flush();
                    outStream.close();
                }
            }
        }
    }

    /**
     * @param fromFile 被复制的文件
     * @param toFile   复制的目录文件
     * @param rewrite  是否重新创建文件
     *
     *                 <p>
     *                 文件的复制操作方法
     */
    public static boolean copyfile(File fromFile, File toFile, Boolean rewrite) {

        if (!fromFile.exists()) {
            return false;
        }

        if (!fromFile.isFile()) {
            return false;
        }
        if (!fromFile.canRead()) {
            return false;
        }
        if (!toFile.getParentFile().exists()) {
            toFile.getParentFile().mkdirs();
        }
        if (toFile.exists() && rewrite) {
            toFile.delete();
        }

        try {
            FileInputStream fosfrom = new FileInputStream(fromFile);
            FileOutputStream fosto = new FileOutputStream(toFile);

            byte[] bt = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            // 关闭输入、输出流
            fosfrom.close();
            fosto.close();
            return true;

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    /*
     * 递归获得文件夹大小
     */
    public static long getFolderSize(File file) {
        long size = 0;
        if (isHasSDCard()) {
            if (!file.exists())
                return 0;

            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    size += getFolderSize(files[i]);
                } else {
                    size += files[i].length();
                }
            }
        }
        return size;
    }

    public static long getFileSize(File file) {
        long size = 0;
        if (isHasSDCard()) {
            if (file.exists())
                return file.length();
        }
        return size;
    }

    /*
     * 获得网络文件大小
     */
    public static InputStream getRemoteInputStream(String url, boolean closed) {
        InputStream is = null;
        if (NetworkUtils.isNetworkAvailable()) {
            try {
                MyLog.p("URL-->" + url);
                URL infoUrl = new URL(url);
                URLConnection connection = infoUrl.openConnection();
                connection.setConnectTimeout(60 * 1000);
                connection.setReadTimeout(60 * 1000);
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
//                httpConnection.setRequestProperty("Accept-Encoding", "identity");
//                httpConnection.setRequestProperty("Charset", "UTF-8");
//                httpConnection.setRequestMethod("GET");
                int responseCode = httpConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    is = httpConnection.getInputStream();
                }
                if (closed)
                    httpConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return is;
    }

    public static long getRemoteFileSize(String url) {
        long size = -1;
        if (NetworkUtils.isNetworkAvailable()) {
            try {
                MyLog.p("URL-->" + url);
                URL infoUrl = new URL(url);
                URLConnection connection = infoUrl.openConnection();
                connection.setConnectTimeout(60 * 1000);
                connection.setReadTimeout(60 * 1000);
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                int responseCode = httpConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        size = connection.getContentLengthLong();
                    } else {
                        size = connection.getContentLength();
                    }
                }
                httpConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return size;
    }

    /*
     * 删除文件及其下面的子文件
     */
    public static void delFile(File file) {
        if (isHasSDCard()) {
            if (!file.exists())
                return;
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    delFile(files[i]); // 删除下面子文件或文件夹
                    files[i].delete(); // 删除自个儿
                } else {
                    files[i].delete(); // 文件直接删掉
                }
            }
        }
    }

    /*
     * 图片压缩
     *
     * @param file :待压缩源文件
     *
     * @param size ：压缩大小
     *
     * @param path ：压缩
     */
    public static File compressImg(File file, long size, String path)
            throws IOException {
        OutputStream os = null;
        Bitmap btm = null;
        if (isHasSDCard()) {
            if (!file.exists() || file.length() < size) // 若文件不存在，或者小于size，则不进行压缩
                return file;

            try {
                File tmpfile = new File(path, "tmp.jpg");

                while (file.length() > size) {
                    // 对图片进行压缩，是在读取的过程中进行压缩，而不是把图片读进了内存再进行压缩
                    BitmapFactory.Options newOpts = new BitmapFactory.Options();
                    // 缩放的比例，缩放是很难按准备的比例进行缩放的，目前我只发现只能通过inSampleSize来进行缩放，其值表明缩放的倍数，SDK中建议其值是2的指数值
                    newOpts.inSampleSize = 2;
                    // inJustDecodeBounds设为false表示把图片读进内存中
                    newOpts.inJustDecodeBounds = false;
                    // 设置大小，这个一般是不准确的，是以inSampleSize的为准，但是如果不设置却不能缩放
                    btm = BitmapFactory.decodeFile(file.getAbsolutePath(),
                            newOpts);

                    // 创建文件输出流
                    if (btm == null) {
                        return file;
                    }
                    tmpfile = new File(path, "tmp.jpg");
                    os = new FileOutputStream(tmpfile);
                    // 存储
                    btm.compress(CompressFormat.JPEG, 100, os);
                    // 关闭流
                    os.flush();
                    os.close();
                    if (!btm.isRecycled()) {
                        btm.recycle();
                    }
                    file = new File(path + file.getName());
                    tmpfile.renameTo(file);
                }
                return file;
            } catch (Exception e) {
                return file;
            }
        }
        return file;
    }

    /*
     * zip解压
     *
     * AssetManager assetManager = getAssets(); // 需要解压的对象 InputStream
     * dataSource = assetManager.open("ShiningTrip.zip"); // 調用解压的方法
     * ZipUtil.unzip(dataSource,
     * android.os.Environment.getExternalStorageDirectory() + "");
     */
    public static void unzip(InputStream zipFileName, String outputDirectory) {
        try {
            ZipInputStream in = new ZipInputStream(zipFileName);
            // 获取ZipInputStream中的ZipEntry条目，一个zip文件中可能包含多个ZipEntry，
            // 当getNextEntry方法的返回值为null，则代表ZipInputStream中没有下一个ZipEntry，
            // 输入流读取完成；
            ZipEntry entry = in.getNextEntry();
            while (entry != null) {

                // 创建以zip包文件名为目录名的根目录
                if (FileUtils.isHasSDCard()) {
                    File file = new File(outputDirectory);
                    file.mkdir();
                    if (entry.isDirectory()) {
                        String name = entry.getName();
                        name = name.substring(0, name.length() - 1);

                        file = new File(outputDirectory + File.separator + name);
                        file.mkdir();
                    } else {
                        file = new File(outputDirectory + File.separator
                                + entry.getName());
                        file.createNewFile();
                        FileOutputStream out = new FileOutputStream(file);
                        int b;
                        while ((b = in.read()) != -1) {
                            out.write(b);
                        }
                        out.close();
                    }
                    // 读取下一个ZipEntry
                    entry = in.getNextEntry();
                }
            }
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 压缩文件（例如图片） --->返回要判断是否为null
    public static File compressImg(File file, int o) throws IOException {
        OutputStream os = null;
        Bitmap btm = null;
        File tmpfile = null;
//if(true) return file;
        // 文件不存在
        if (!file.exists()) {
            return null;
        }

        System.out.println(file.length() + "---------");
        // 若文件小于指定大小，则不进行压缩
        if (file.length() > BaseConstants.FILE_IMAGE_MAXSIZE) {
            try {
                String path = BaseConstants.CACHE_SAVE_IMG_PATH;
                tmpfile = new File(path);
                if (!tmpfile.exists()) {
                    tmpfile.mkdirs();
                }
                tmpfile = new File(path, "tmp.jpg");

//					while (file.length() > BaseConstants.FILE_IMAGE_MAXSIZE) {
                btm = BitmapFactory
                        .decodeFile(file.getAbsolutePath());
//						btm = BitmapFactory.decodeStream(new FileInputStream(file));
                // 创建文件输出流
                if (btm == null) {
                    return file;
                }

                tmpfile = new File(path, "tmp.jpg");
                os = new FileOutputStream(tmpfile);
                // 存储
                btm.compress(CompressFormat.JPEG, 10, os);

                System.out.println(tmpfile.length() + "---------");
                // 关闭流
                os.flush();
                os.close();
                if (btm != null && !btm.isRecycled()) {
                    btm.recycle();
                }
                file = new File(path + file.getName());
                tmpfile.renameTo(file);
//					}
            } catch (Exception e) {
                return null;
            }
        }

        return file;
    }

    // 压缩文件（例如图片） --->返回要判断是否为null
    public static File compressImg(File file) throws IOException {
        String orientation = "";
        int angle = 0;
        Bitmap mBitmap = null;
        Bitmap tmpBitmap = null;
        OutputStream os = null;
        Bitmap btm = null;

        // 文件不存在
        if (!file.exists()) {
            return null;
        }

        String filepath = file.getAbsolutePath();
        orientation = ImageUtils.getOrientation(filepath);

        // 若文件小于指定大小，则不进行压缩
        if (file.length() > BaseConstants.FILE_IMAGE_MAXSIZE) {
            try {
                String path = BaseConstants.CACHE_SAVE_IMG_PATH;
                File tmpfile = new File(path);
                if (!tmpfile.exists()) {
                    tmpfile.mkdirs();
                }
                tmpfile = new File(path, "tmp.jpg");

                while (file.length() > BaseConstants.FILE_IMAGE_MAXSIZE) {

                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    // 缩放的比例，缩放是很难按准备的比例进行缩放的，目前我只发现只能通过inSampleSize来进行缩放，其值表明缩放的倍数，SDK中建议其值是2的指数值
                    opts.inSampleSize = 2;
                    // inJustDecodeBounds设为false表示把图片读进内存中
                    opts.inJustDecodeBounds = false;
                    // 设置大小，这个一般是不准确的，是以inSampleSize的为准，但是如果不设置却不能缩放
                    btm = BitmapFactory
                            .decodeFile(file.getAbsolutePath(), opts);

                    // 创建文件输出流
                    if (btm == null) {
                        return file;
                    }

                    tmpfile = new File(path, "tmp.jpg");
                    os = new FileOutputStream(tmpfile);
                    // 存储
                    btm.compress(CompressFormat.JPEG, 100, os);
                    // 关闭流
                    os.flush();
                    os.close();
                    if (btm != null && !btm.isRecycled()) {
                        btm.recycle();
                    }
                    file = new File(path + file.getName());
                    tmpfile.renameTo(file);
                }
            } catch (Exception e) {
                return null;
            }
        }

        return file;
    }

    // 压缩文件
    public static File compressiconImg(File file, int size) throws IOException {
        String orientation = "";
        OutputStream os = null;
        // 文件不存在
        if (!file.exists()) {
            return null;
        }
        String filepath = file.getAbsolutePath();
        orientation = ImageUtils.getOrientation(filepath);

        // 若文件小于指定大小，则不进行压缩
//			if (file.length() > BaseConstants.FILE_IMAGE_ICONSIZE) {
        try {
            String path = BaseConstants.CACHE_SAVE_IMG_PATH;
            File tmpfile = new File(path);
            if (!tmpfile.exists()) {
                tmpfile.mkdirs();
            }

            BitmapFactory.Options options = new BitmapFactory.Options();
            // 获取这个图片的宽和高
            Bitmap bitmap = BitmapFactory.decodeFile(filepath, options); //此时返回bm为空
            options.inJustDecodeBounds = false;
            // 获得图片的宽高
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            // 计算缩放比例
            float scaleWidth = ((float) size) / width;
            float scaleHeight = ((float) size) / height;
            // 取得想要缩放的matrix参数
            Matrix matrix = new Matrix();
            matrix.postScale(scaleWidth, scaleHeight);
            // 得到新的图片   www.2cto.com
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);


            // 创建文件输出流
            if (bitmap == null) {
                return file;
            }

            tmpfile = new File(path, "tmp.jpg");
            os = new FileOutputStream(tmpfile);
            // 存储
            bitmap.compress(CompressFormat.JPEG, 75, os);
            // 关闭流
            os.flush();
            os.close();
            if (bitmap != null && !bitmap.isRecycled()) {
                bitmap.recycle();
            }
            file = new File(path + file.getName());
            tmpfile.renameTo(file);

        } catch (Exception e) {
            return null;
        }
//			}			
        return file;
    }

//		// 压缩文件
//		public static File compressImg(File file,int width) throws IOException {
//					String orientation = "";			
//					OutputStream os = null;			
//					// 文件不存在
//					if (!file.exists()) {
//						return null;
//					}
//					String filepath = file.getAbsolutePath();
//					orientation = ImageUtils.getOrientation(filepath);
//
//					// 若文件小于指定大小，则不进行压缩
////					if (file.length() > BaseConstants.FILE_IMAGE_ICONSIZE) {
//						try {
//							String path = BaseConstants.CACHE_SAVE_IMG_PATH;
//							File tmpfile = new File(path);
//							if (!tmpfile.exists()) {
//								tmpfile.mkdirs();
//							} 
//												
//						    BitmapFactory.Options options = new BitmapFactory.Options();			    
//					        // 获取这个图片的宽和高
//					        Bitmap bitmap = BitmapFactory.decodeFile(filepath, options); //此时返回bm为空
//					        options.inJustDecodeBounds = false;			        
//					        bitmap=ImageUtils.getImageThumbnail(filepath, width);
//										     	
//							// 创建文件输出流
//							if (bitmap == null) {
//								return file;
//							}
//			
//							tmpfile = new File(path, "tmp.jpg");
//							os = new FileOutputStream(tmpfile);
//							// 存储
//							bitmap.compress(CompressFormat.JPEG, 75, os);
//							// 关闭流
//							os.flush();   
//							os.close();  
//							if (bitmap != null && !bitmap.isRecycled()) {
//								bitmap.recycle(); 
//							}  
//							file = new File(path + file.getName());
//							tmpfile.renameTo(file);
//							
//						} catch (Exception e) {
//							return null;
//						}
////					}			
//					return file;
//				}

    /**
     * 判断文件是否为图片文件(GIF,PNG,JPG)
     *
     * @param srcFileName
     * @return
     */
    public static boolean isImage(String srcFileName) {
        boolean isImage = false;
        if (!srcFileName.contains(".")) {
            return isImage;
        }
        String imagetype = srcFileName.substring(srcFileName.lastIndexOf("."));

        if (imagetype.equalsIgnoreCase(".jpg")
                || imagetype.equalsIgnoreCase(".gif")
                || imagetype.equalsIgnoreCase(".jpeg")
                || imagetype.equalsIgnoreCase(".bmp")
                || imagetype.equalsIgnoreCase(".png")) {
            isImage = true;
        }
        return isImage;
    }

    // 删除numDays之前的文件夹
    public static int clearCacheFolder(File dir, long numDays) {
        int deletedFiles = 0;
        if (dir != null && dir.isDirectory()) {
            try {
                for (File child : dir.listFiles()) {
                    if (child.isDirectory()) {
                        deletedFiles += clearCacheFolder(child, numDays);
                    }
                    if (child.lastModified() < numDays) {
                        if (child.delete()) {
                            deletedFiles++;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return deletedFiles;
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName
     * @return
     */
    public static String getFileFormat(String fileName) {
        if (StringUtils.isEmpty(fileName))
            return "";

        int point = fileName.lastIndexOf('.');
        return fileName.substring(point + 1);
    }

    /**
     * InputStream转Byte
     *
     * @param in
     * @return
     * @throws IOException
     */
    public static byte[] InputStreamToByte(InputStream in) throws IOException {
        int BUFFER_SIZE = 4096;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[BUFFER_SIZE];
        int count = -1;
        while ((count = in.read(data, 0, BUFFER_SIZE)) != -1)
            outStream.write(data, 0, count);

        data = null;
        return outStream.toByteArray();
    }

    /**
     * Get PlantWorkStatusInfo1 file path from PlantWorkStatusInfo1 Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri     The Uri to query.
     * @author paulburke
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically PlantWorkStatusInfo1 file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /*
     * 由URI的到绝对路径
     */
    public static String getAbsoluteImagePath(Activity activity, Uri uri) {
        // can post image
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = activity.managedQuery(uri, proj, // Which columns to
                // return
                null, // WHERE clause; which rows to return (all rows)
                null, // WHERE clause selection arguments (none)
                null); // Order-by clause (ascending by name)

        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    /**
     * 把assets文件夹下的文件拷到sd卡
     *
     * @param context
     * @param assetsFilename
     * @param desPath
     * @throws IOException
     */

    public static void copyAssetsFileToSd(Context context, String assetsFilename, String desPath) throws IOException {
        InputStream inputStream = context.getAssets().open(assetsFilename);
        FileOutputStream out = new FileOutputStream(desPath);
        byte[] buffer = new byte[1024];
        int n = 0;
        while (-1 != (n = inputStream.read(buffer))) {
            out.write(buffer, 0, n);
        }
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            if (out != null) out.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static String getFromAssets(Context context, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            InputStreamReader inputReader = new InputStreamReader(context.getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            while ((line = bufReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param filePath
     * @return 带后缀
     */
    public static String getFileNameWithSuffix(@NonNull String filePath) {
        String[] splits = filePath.split("/");
        return splits[splits.length - 1];
    }

}
